package net.zhaolei.zhaolei_redis.controller;

import net.zhaolei.zhaolei_redis.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/coupon")
public class CouponController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("add")
    public JsonData saveCoupon(@RequestParam(value = "coupon_id", required = true) int couponId) {
        String uuid = UUID.randomUUID().toString();

        String lockKey = "lock:coupon:" + couponId;

        lock(couponId, uuid, lockKey);

        return JsonData.buildSuccess();
    }

    private void lock(int couponId, String uuid, String lockKey) {
        //lua script
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

        Boolean nativeLock = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, uuid, Duration.ofSeconds(30));
        System.out.println(uuid+"枷锁状态"+nativeLock);

        if (nativeLock) {
            // lock success

            try {
                TimeUnit.SECONDS.sleep(1L);
            } catch (InterruptedException e) {

            } finally {
                //解锁，把判断和删除操作结合在一起了
                Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockKey), uuid);
                System.out.println("解锁状态:"+result);
            }
        } else {
            //自旋操作
            try {
                System.out.println("枷锁失败，睡眠5秒，进行自旋");
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {}

            lock(couponId, uuid, lockKey);
        }
    }
}
